<script setup>
import {GetCateDetail, GetGoodsList, UpdateGoodsList, DelGoodsInfoById} from "@/api/shopCate"
import dayjs from "dayjs"
import {computed, ref} from "vue"
import {ElMessage} from 'element-plus'
import {Upload} from "@element-plus/icons-vue";

const params = ref({
  page: 1,
  pageSize: 10,
  keyword: undefined,
  cateId: undefined
})

const options = ref([]) // 分类类型
const dialogInfo = ref({
  visible: false,
  isEdit: false
})
const form = ref({})
const insertSwipeInfo = ref({
  visible: false,
  idEdit: false,
})
const swipeInfo = ref({})


// 获取分类列表
const getCateType = async () => {
  const res = await GetCateDetail({page: 1, pageSize: 100})
  options.value = res.records
}

const findTypeById = (cateId) => {
  return options.value.find(item => item.id === cateId)?.title
}

getCateType()

const data = ref([])
const total = ref(0)
const getData = async () => {
  try {
    const res = await GetGoodsList(params.value)
    data.value = res.records
    total.value = res.total
  } catch (e) {
  }
}
getData()

// 编辑或新增事件
const EditHandler = (row) => {
  dialogInfo.value.isEdit = Boolean(row.id)
  dialogInfo.value.visible = true
  form.value = Boolean(row.id) ? {...row} : {swipeInfo: [], goodsNorms: []}
  if (form.value.swipeInfo && form.value.swipeInfo.length) {
    form.value.swipeInfo.forEach((item, index) => {
      item['index'] = index
    })
  }
}

// 删除事件
const DelHandler = async (row) => {
  try {
    await DelGoodsInfoById(row.id)
    await getData()
    ElMessage.success("删除完成")
  } catch (e) {
  }
}

const handleSizeChange = (size) => {
  params.value.pageSize = size
  getData()
}

const handleCurrentChange = (page) => {
  params.value.page = page
  getData()
}

// 提交表单
const submitForm = async () => {
  try {
    await UpdateGoodsList(form.value)
    dialogInfo.value.visible = false
    ElMessage.success(`${dialogInfo.value.isEdit ? "编辑" : "新增"}完成`)
    await getData()
  } catch (e) {
  }
}

const updateSwipeInfo = (row) => {
  insertSwipeInfo.value.isEdit = Boolean(row.url)
  insertSwipeInfo.value.visible = true
  swipeInfo.value = {...row}
}

// 新增轮播信息数据
const swipeSubmit = () => {
  // 有序号为编辑
  if (insertSwipeInfo.value.isEdit) {
    form.value.swipeInfo.splice(swipeInfo.value.index, 1, {...swipeInfo.value})
  } else {
    console.log(form.value)
    form.value.swipeInfo.push({...swipeInfo.value, index: form.value.swipeInfo.length})
  }
  insertSwipeInfo.value.visible = false
}

// 删除轮播信息
const delSwipeInfo = (index) => {
  form.value.swipeInfo.splice(index, 1)
  form.value.swipeInfo.forEach((item, index) => {
    item['index'] = index
  })
}

// 新增规格方法
const addNorm = () => {
  form.value.goodsNorms.push({
    desc: '',
    index: form.value.goodsNorms.length
  })
}

const reduceNorm = () => {
  form.value.goodsNorms.pop()
}
</script>

<template>
  <el-card>
    <div class="mb-[20px] flex justify-between">
      <div class="w-[42%] flex">
        <el-input placeholder="请搜索关键字" v-model="params.keyword" clearable @clear="getData"></el-input>
        <el-select v-model="params.cateId" placeholder="请选择分类类型" class="ml-[10px]" clearable @clear="getData">
          <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.title"
              :value="item.id"
          />
        </el-select>
        <el-button type="success" class="ml-[10px]" @click="getData">查询</el-button>
      </div>
      <el-button type="primary" @click="EditHandler">新增</el-button>
    </div>
    <el-table :data="data" border stripe>
      <el-table-column label="ID" prop="id"></el-table-column>
      <el-table-column label="标题" prop="title" min-width="180"></el-table-column>
      <el-table-column label="分类" width="120">
        <template #default="{row}">
          <el-tag>{{ findTypeById(row.cateId) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="封面图">
        <template #default="{row}">
          <el-image class="w-[60px] h-[60px]" :src="row.banner"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="销量" prop="sale"></el-table-column>
      <el-table-column label="评分">
        <template #default="{row}">
          {{ row.score.toFixed(1) }}
        </template>
      </el-table-column>
      <el-table-column label="价格">
        <template #default="{row}">
          {{ row.price.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column label="库存" prop="stock"></el-table-column>
      <el-table-column label="创建时间" min-width="180">
        <template #default="{row}">
          {{ dayjs(row.createTime).format("YYYY-MM-DD HH:mm:ss") }}
        </template>
      </el-table-column>
      <el-table-column label="更新时间" min-width="180">
        <template #default="{row}">
          {{ dayjs(row.updateTime).format("YYYY-MM-DD HH:mm:ss") }}
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="150" fixed="right">
        <template #default="{row}">
          <el-button type="primary" size="small" @click="EditHandler(row)">编辑</el-button>
          <el-button type="danger" size="small" @click="DelHandler(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="mt-[10px] flex justify-end">
      <el-pagination
          v-model:currentPage="params.page"
          v-model:page-size="params.pageSize"
          :page-sizes="[5,10, 20, 30, 40]"
          size="small"
          layout="total, sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </el-card>
  <Dialog :title="dialogInfo.isEdit ? '编辑' : '新增'" v-model:visible="dialogInfo.visible" width="800px" height="500px"
          @onSubmit="submitForm">
    <el-form label-width="80px" label-position="left">
      <el-row :gutter="20" class="w-full">
        <el-col :span="12">
          <el-form-item label="标题">
            <el-input v-model="form.title" placeholder="请选择标题"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="分类">
            <el-select v-model="form.cateId" placeholder="请选择分类类型" class="ml-[10px]">
              <el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20" class="w-full">
        <el-col :span="12">
          <el-form-item label="价格">
            <el-input v-model="form.price" placeholder="请填写价格"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="库存">
            <el-input v-model="form.stock" placeholder="请填写库存"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="封面图">
            <UpLoad v-model:images="form.banner"></UpLoad>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="销量">
            <el-input v-model="form.sale" placeholder="请填写销量"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="评分">
            <el-input v-model="form.score" placeholder="请填写评分"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item label="描述">
            <Editor v-if="dialogInfo.visible" v-model:value="form.description"></Editor>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item label="规格信息">
            <div class="w-full pb-[20px]" v-if="form.goodsNorms && form.goodsNorms.length">
              <TransitionGroup name="list">
                <div v-for="(item,index) in form.goodsNorms" :key="index" class="w-[75%] flex mb-[10px]">
                  <el-input v-model="item.desc" placeholder="请输入规格"></el-input>
                  <div class="flex ml-[10px]" v-show="index == form.goodsNorms.length - 1">
                    <el-button type="success" icon="Plus" @click="addNorm"></el-button>
                    <el-button type="danger" icon="CloseBold" @click="reduceNorm"></el-button>
                  </div>
                </div>
              </TransitionGroup>
            </div>
            <el-button type="primary" v-else @click="addNorm">添加规格</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="轮播信息图">
        <el-button type="primary" class="mb-[10px]" @click="updateSwipeInfo">新增信息图</el-button>
        <el-table :data="form.swipeInfo" border stripe>
          <el-table-column prop="index" label="序号" width="100"></el-table-column>
          <el-table-column label="图片">
            <template #default="{row}">
              <el-image class="w-[60px] h-[60px]" :src="row.url"></el-image>
            </template>
          </el-table-column>
          <el-table-column label="是否显示">
            <template #default="{row}">
              <el-tag v-if="row.isShow == 1">显示</el-tag>
              <el-tag v-else type="warning">隐藏</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="排序" prop="sort"></el-table-column>
          <el-table-column>
            <template #default="{row}">
              <el-button type="primary" size="small" @click="updateSwipeInfo(row)">编辑</el-button>
              <el-button type="danger" size="small" @click="delSwipeInfo(index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
  </Dialog>
  <Dialog v-model:visible="insertSwipeInfo.visible" :title="`${insertSwipeInfo.isEdit ? '编辑': '新增'}信息图`"
          @onSubmit="swipeSubmit">
    <el-form label-width="100" label-position="left">
      <el-form-item label="图片">
        <UpLoad v-model:images="swipeInfo.url"></UpLoad>
      </el-form-item>
      <el-form-item label="是否显示">
        <el-select v-model="swipeInfo.isShow" placeholder="请选择分类类型" class="ml-[10px]">
          <el-option
              label="显示"
              :value="1"
          />
          <el-option
              label="隐藏"
              :value="2"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="排序" class="w-[200px]">
        <el-input placeholder="请输入排序" v-model="swipeInfo.sort"></el-input>
      </el-form-item>
    </el-form>
  </Dialog>
</template>

<style scoped lang="scss">
.list-move, /* 对移动中的元素应用的过渡 */
.list-enter-active,
.list-leave-active {
  transition: all 0.5s ease;
}

.list-enter-from,
.list-leave-to {
  opacity: 0;
  transform: translateX(30px);
}

/* 确保将离开的元素从布局流中删除
  以便能够正确地计算移动的动画。 */
.list-leave-active {
  position: absolute;
}
</style>
